<template>
  <div class="user-management">
    <div class="page-header">
      <h2>用户管理</h2>
      <a-button type="primary" @click="showAddModal">
        <PlusOutlined />
        添加用户
      </a-button>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-section">
      <a-row :gutter="16">
        <a-col :span="6">
          <a-input
            v-model:value="searchParams.userName"
            placeholder="搜索用户名"
            @pressEnter="handleSearch"
          >
            <template #prefix>
              <SearchOutlined />
            </template>
          </a-input>
        </a-col>
        <a-col :span="6">
          <a-input
            v-model:value="searchParams.userAccount"
            placeholder="搜索账号"
            @pressEnter="handleSearch"
          />
        </a-col>
        <a-col :span="6">
          <a-select
            v-model:value="searchParams.userRole"
            placeholder="选择角色"
            allowClear
            @change="handleSearch"
          >
            <a-select-option value="admin">管理员</a-select-option>
            <a-select-option value="user">普通用户</a-select-option>
          </a-select>
        </a-col>
        <a-col :span="6">
          <a-space>
            <a-button type="primary" @click="handleSearch">
              <SearchOutlined />
              搜索
            </a-button>
            <a-button @click="handleReset">
              <ReloadOutlined />
              重置
            </a-button>
          </a-space>
        </a-col>
      </a-row>
    </div>

    <!-- 用户列表表格 -->
    <div class="table-section">
      <a-table
        :columns="columns"
        :data-source="userList"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'userAvatar'">
            <a-avatar :src="record.userAvatar" :size="40">
              {{ record.userName?.charAt(0) }}
            </a-avatar>
          </template>
          
          <template v-if="column.key === 'userRole'">
            <a-tag :color="record.userRole === 'admin' ? 'red' : 'blue'">
              {{ record.userRole === 'admin' ? '管理员' : '普通用户' }}
            </a-tag>
          </template>
          
          <template v-if="column.key === 'gender'">
            <span>{{ record.gender === 0 ? '女' : record.gender === 1 ? '男' : '未知' }}</span>
          </template>
          
          <template v-if="column.key === 'createTime'">
            <span>{{ formatDate(record.createTime) }}</span>
          </template>
          
          <template v-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="showEditModal(record)">
                <EditOutlined />
                编辑
              </a-button>
              <a-popconfirm
                title="确定要删除这个用户吗？"
                @confirm="handleDelete(record.id)"
              >
                <a-button type="link" size="small" danger>
                  <DeleteOutlined />
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>

    <!-- 添加/编辑用户模态框 -->
    <a-modal
      v-model:open="modalVisible"
      :title="isEdit ? '编辑用户' : '添加用户'"
      @ok="handleSubmit"
      @cancel="handleCancel"
      :confirmLoading="submitLoading"
    >
      <a-form
        :model="formData"
        :rules="formRules"
        ref="formRef"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-item label="用户名" name="userName">
          <a-input v-model:value="formData.userName" placeholder="请输入用户名" />
        </a-form-item>
        
        <a-form-item label="账号" name="userAccount">
          <a-input v-model:value="formData.userAccount" placeholder="请输入账号" />
        </a-form-item>
        
        <a-form-item label="密码" name="userPassword" v-if="!isEdit">
          <a-input-password v-model:value="formData.userPassword" placeholder="请输入密码" />
        </a-form-item>
        
        <a-form-item label="头像" name="userAvatar">
          <a-input v-model:value="formData.userAvatar" placeholder="请输入头像URL" />
        </a-form-item>
        
        <a-form-item label="性别" name="gender">
          <a-radio-group v-model:value="formData.gender">
            <a-radio :value="0">女</a-radio>
            <a-radio :value="1">男</a-radio>
          </a-radio-group>
        </a-form-item>
        
        <a-form-item label="角色" name="userRole">
          <a-select v-model:value="formData.userRole" placeholder="请选择角色">
            <a-select-option value="admin">管理员</a-select-option>
            <a-select-option value="user">普通用户</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import {
  PlusOutlined,
  SearchOutlined,
  ReloadOutlined,
  EditOutlined,
  DeleteOutlined
} from '@ant-design/icons-vue'
import {
  listUserByPageUsingGet,
  addUserUsingPost,
  updateUserUsingPost,
  deleteUserUsingPost
} from '@/api/userController'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const modalVisible = ref(false)
const isEdit = ref(false)
const userList = ref([])
const formRef = ref()

// 搜索参数
const searchParams = reactive({
  userName: undefined,
  userAccount: undefined,
  userRole: undefined,
  current: 1,
  pageSize: 10
})

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total) => `共 ${total} 条记录`
})

// 表单数据
const formData = reactive({
  id: undefined,
  userName: '',
  userAccount: '',
  userPassword: '',
  userAvatar: '',
  gender: 1,
  userRole: 'user'
})

// 表单验证规则
const formRules = {
  userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  userAccount: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  userPassword: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  userRole: [{ required: true, message: '请选择角色', trigger: 'change' }]
}

// 表格列配置
const columns = [
  {
    title: '头像',
    dataIndex: 'userAvatar',
    key: 'userAvatar',
    width: 80
  },
  {
    title: '用户名',
    dataIndex: 'userName',
    key: 'userName'
  },
  {
    title: '账号',
    dataIndex: 'userAccount',
    key: 'userAccount'
  },
  {
    title: '角色',
    dataIndex: 'userRole',
    key: 'userRole'
  },
  {
    title: '性别',
    dataIndex: 'gender',
    key: 'gender'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime'
  },
  {
    title: '操作',
    key: 'action',
    width: 150
  }
]

// 获取用户列表
const fetchUserList = async () => {
  try {
    loading.value = true
    const params = {
      ...searchParams,
      current: pagination.current,
      pageSize: pagination.pageSize
    }
    
    const response = await listUserByPageUsingGet(params)
      console.log(response)
    userList.value = response.records || []
    pagination.total = response.total || 0
    
  } catch (error) {
    console.error('获取用户列表失败：', error)
    message.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchUserList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchParams, {
    userName: '',
    userAccount: '',
    userRole: undefined,
    current: 1,
    pageSize: 10
  })
  pagination.current = 1
  fetchUserList()
}

// 表格变化处理
const handleTableChange = (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchUserList()
}

// 显示添加模态框
const showAddModal = () => {
  isEdit.value = false
  modalVisible.value = true
  resetForm()
}

// 显示编辑模态框
const showEditModal = (record) => {
  isEdit.value = true
  modalVisible.value = true
  Object.assign(formData, record)
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: undefined,
    userName: '',
    userAccount: '',
    userPassword: '',
    userAvatar: '',
    gender: 1,
    userRole: 'user'
  })
  formRef.value?.resetFields()
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    if (isEdit.value) {
      await updateUserUsingPost(formData)
      message.success('用户更新成功')
    } else {
      await addUserUsingPost(formData)
      message.success('用户添加成功')
    }
    
    modalVisible.value = false
    fetchUserList()
    
  } catch (error) {
    console.error('提交失败：', error)
    message.error(error.message || '操作失败')
  } finally {
    submitLoading.value = false
  }
}

// 取消模态框
const handleCancel = () => {
  modalVisible.value = false
  resetForm()
}

// 删除用户
const handleDelete = async (id) => {
  try {
    await deleteUserUsingPost({ id })
    message.success('用户删除成功')
    fetchUserList()
  } catch (error) {
    console.error('删除失败：', error)
    message.error('删除失败')
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString('zh-CN')
}

// 组件挂载时获取数据
onMounted(() => {
  fetchUserList()
})
</script>

<style scoped>
.user-management {
  padding: 24px;
  background: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  background: white;
  padding: 16px 24px;
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);
}

.page-header h2 {
  margin: 0;
  color: #333;
  font-size: 20px;
  font-weight: 600;
}

.search-section {
  background: white;
  padding: 24px;
  border-radius: 8px;
  margin-bottom: 24px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);
}

.table-section {
  background: white;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-management {
    padding: 16px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .search-section .ant-row {
    flex-direction: column;
  }
  
  .search-section .ant-col {
    width: 100% !important;
    max-width: 100% !important;
    margin-bottom: 16px;
  }
}
</style>
